<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Token extends Model
{
    protected $table = 'dd_token';
    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $guarded = array();
    public static function getToken($type, $openid="") {
        if ($type == 1) {
           $where = "type = 1 and validity > ".time();
        } else if($type == 2 && !empty($openid)) {
            $where = "type = 2 and validity > ".time();
        } else {
            return [
                "status"    => 0,
                "info"      => "没有填写openid"
            ];
        }
        $token = static::whereRaw($where)->first();
        if (!$token) {
            $tk = new static();
            $resToken = $tk->token();
            if(is_array($resToken)) {
                return $resToken;
            }
            $res = static::firstOrCreate(['type'=>1]);
            $res->token = $resToken->access_token;
            $res->validity = $resToken->expires_in + time();
            $res->save();
            return [
                'status'    => 1,
                'info'      => $resToken->access_token
            ];
        }
        return [
            'status'    => 1,
            'info'      => $token->token
        ];
    }
    
    private function token() {
        $appid      = env('WECHAT_APPID');
        $appsecret  = env('WECHAT_APPSECRET'); 
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        //curl获取token 信息
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        $res = curl_exec($ch);
        curl_close($ch);
        $resObj = json_decode($res);
        if ($resObj->access_token) {
            return $resObj;
        } else {
            return [
                "status"    => 0,
                "info"      => $resObj->errmsg
            ];
        }
    }
}
